package com.autoagent.ai_live_master.common.utils;

import com.autoagent.ai_live_master.common.config.JWTUtilsProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
@Slf4j
@Component
public class JwtUtils {
    @Autowired
    private JWTUtilsProperties jwtUtilsProperties;
    /**
     * 生成JWT令牌
     * @param claims JWT第二部分负载 payload 中存储的内容
     * @return
     */
    public String generateJwt(Map<String, Object> claims){
        String signKey = jwtUtilsProperties.getSignKey();
        Long expire=jwtUtilsProperties.getExpire();
        return Jwts.builder()
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, signKey)
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .compact();
    }

    /**
     * 解析JWT令牌
     * @param jwt JWT令牌
     * @return JWT第二部分负载 payload 中存储的内容
     */
    public Claims parseJWT(String jwt) {
        log.info("开始解析 JWT 令牌: {}", jwt);
        String signKey = jwtUtilsProperties.getSignKey();
        log.info("使用的签名密钥: {}", signKey);
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(signKey)
                    .parseClaimsJws(jwt)
                    .getBody();
            log.info("JWT 令牌解析成功: {}", claims);
        } catch (Exception e) {
            log.error("JWT 令牌解析失败: {}", e.getMessage(), e);
        }
        return claims;
    }
}
